package com.lesserpand.springcloudalibabacore.config.redis.redissonquery.utils;

import org.redisson.Redisson;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author bailuo
 * @version 2.0
 * @Description TODO
 * @Date Created in 2019/1/17 17:28
 */
@Component
public class RedissonUtils {


    @Autowired
    private Redisson redisson;

    /**
     * 消息延迟之后发送到指定的队列
     *
     * @param queueName 指定队列名称
     * @param message   消息
     * @param timeout   超时时间
     * @param timeUnit  超时单位， 如分钟：TimeUnit.MINUTES
     */
    public String sendMessageQueue(String queueName, String message, Long timeout, TimeUnit timeUnit) {
        // 真正的消息队列
        RQueue<String> distinationQueue = redisson.getQueue(queueName);
        // 延迟队列，消息到时间后发送到真正的消息队列
        RDelayedQueue<String> delayedQueue = redisson.getDelayedQueue(distinationQueue);
        // timeout以后将消息发送到指定队列
        delayedQueue.offer(message, timeout, timeUnit);
        return "放入延迟队列";
    }

    /**
     * 获取指定队列的消息
     *
     * @param queueName 指定队列名称
     * @return
     */
    public String getMessageQueue(String queueName) {
        RQueue<String> distinationQueue = redisson.getQueue(queueName);
        String msg = distinationQueue.poll();
        return msg;
    }
}
